$(function() {
    $("#right_games_button").bind('click',function() {
        window.location.href = "games.html";
    }) 
	$("#sw_bu").bind('click',function() {
        $("#div2").hide();
        $("#div1").show();
        $("#sw_bu").attr('class', 'countdown_button');
        $("#cd_bu").attr('class', 'stopwatch_button');

    }) 
	$("#cd_bu").bind('click',function() {
        $("#div1").hide();
        $("#div2").show();
        $("#sw_bu").attr('class', 'stopwatch_button');
        $("#cd_bu").attr('class', 'countdown_button');
    })
	$("#start").bind('click',function() {
        $("#start").hide();
        $("#stop").show();
        $("#record").show();
        $("#reset").hide();
        startclock();
		stoppausetime();
    }) 
	$("#stop").bind('click',function() {
        $("#start").show();
        $("#stop").hide();
        $("#record").hide();
        $("#reset").show();
        pauseclock();
		startpausetime();
    })
	$("#record").bind('click',function() {
        var rowCount = $('#clock_table >tbody').length;
        var labename = "Lap" + (rowCount + 1);
        var record = $("#larmTime1").val() + ":" + $("#larmTime2").val() + ":" + $("#larmTime3").val() + ":" + $("#larmTime4").text().split("")[0];
        var second = "--";
		var lastrecord=$("#div_"+rowCount).text();
		if(lastrecord){
			second=dis(record,lastrecord);
		}
		if(pausetime){addpause(pausetime);pausetime=''};
        addrecord(labename, record,second);
    })
	$("#reset").bind('click',function() {
        stopclock();
        $("#larmTime1").val(m > 9 ? m: ("0" + m));
        $("#larmTime2").val(h > 9 ? h: ("0" + h));
        $("#larmTime3").val(s > 9 ? s: ("0" + s));
        $("#larmTime4").html(ss);
        //$("#clock_table").remove();
		$('#clock_table').empty();
    })

});
var pause,pausetime,
h1 = 0,
s1 = 0,
m1 = 0;

var se, m = 0,
h = 0,
s = 0,
ss = 1;

function dis(t2,t1){
	var arr2=t2.split(":");
	var arr1=t1.split(":");
	var sec=(((parseInt(arr2[1])*60+parseInt(arr2[2])+parseInt(arr2[3]))*1000)-((parseInt(arr1[1])*60+parseInt(arr1[2])+parseInt(arr2[3]))*1000))/1000;
	return sec.toFixed(2)+"s";
	
}
  
function second() {
    if ((ss % 100) == 0) {
        s += 1;
        ss = 1;
    }
    if (s > 0 && (s % 60) == 0) {
        m += 1;
        s = 0;
    }
    if (m > 0 && (m % 60) == 0) {
        h += 1;
        m = 0;
    }
    $("#larmTime3").val(s > 9 ? s: ("0" + s));
    $("#larmTime2").val(m > 9 ? m: ("0" + m));
    $("#larmTime1").val(h > 9 ? h: ("0" + h));
    $("#larmTime4").html(ss);
    ss += 1;
}

function startclock() {
    se = setInterval("second()", 10);
}
function pauseclock() {
    clearInterval(se);
}
function stopclock() {
    clearInterval(se);
    ss = 0;
    m = h = s = 0;
}

function startpausetime() {
    pause = setInterval("countpausetime()", 1000);
}

function stoppausetime() {
	pausetime=(h1<10?("0"+h1):h1)+":"+(m1<10?("0"+m1):m1)+":"+(s1<10?("0"+s1):s1);
    clearInterval(pause);
    m1 = h1 = s1 = 0;
}

function countpausetime() {
    
    if (s1 > 0 && (s1 % 60) == 0) {
        m1 += 1;
        s1 = 0;
    }
    if (m1 > 0 && (m1 % 60) == 0) {
        h1 += 1;
        m1 = 0;
    }
    s1 += 1;
}

function addrecord(labname, record, second) {
    var tab = document.getElementById("clock_table");
    var rowCount = $('#clock_table >tbody').length;
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
    var td1 = document.createElement("td");
	td1.style.width = "30% ";
    var div1 = document.createElement("div");
    div1.className = "row1";
    div1.innerHTML = labname;
    td1.appendChild(div1);
    var td2 = document.createElement("td");
    td2.style.width = "50% ";
    var div2 = document.createElement("div");
    div2.className = "row2";
	div2.id="div_"+(rowCount+1);
    div2.innerHTML = record;
    td2.appendChild(div2);
    var td3 = document.createElement("td");
    td3.style.width = "20%";
    td3.innerHTML = second;
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tbody.appendChild(tr);
    tab.appendChild(tbody);
}

function addpause(pausetime){
	var tab = document.getElementById("clock_table");
    var rowCount = $('#clock_table >tbody').length;
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
	var td = document.createElement("td");
	td.setAttribute("colspan", "3");
	td.style.width="100%";
	var div = document.createElement("div");
	div.className="table_paused";
	div.innerHTML="--------Paused:"+pausetime+"--------";
	td.appendChild(div);
	tr.appendChild(td);
	tbody.appendChild(tr);
	tab.appendChild(tbody);
}

$("#stop").bind('click',
function() {

})

/*
* countdown Timer Task
*/
var timer;
var hours, minutes, seconds, milisecond;
var initnumber = '00';
var create = true;
function isNumber(id) {
    var txt = $("#" + id).val();
    var reg = /^[-]{0,1}[0-9]{1,}$/;
    if (reg.test(txt)) {
        if (txt.length <= 2) {
            if (txt.length == 1) {
                $("#" + id).val("0" + txt);
            } else if (txt >= 60) {
                alert("Please enter an integer less than 60");
                return false;
            }
        } else {
            alert("Please enter an integer length is less than two");
            return false;
        }
    } else {
        alert("Please enter an integer");
        return false;
    }
}
var javascript_countdown = function() {
    var time_left = 10; //number of seconds for countdown
    var output_element_id = 'javascript_countdown_time';
    var keep_counting =0;
    var no_time_left_message = 'No time left for JavaScript countdown!';

    function countdown() {
		console.log(time_left);
        if (time_left ==0) {
			no_time_left();
			return;
        }

        time_left = time_left - 1;
    }

    function add_leading_zero(n) {
        if (n.toString().length < 2) {
            return '0' + n;
        } else {
            return n;
        }
    }

    function format_output() {

        seconds = time_left % 60;
        minutes = Math.floor(time_left / 60) % 60;
        hours = Math.floor(time_left / 3600);

        seconds = add_leading_zero(seconds);
        minutes = add_leading_zero(minutes);
        hours = add_leading_zero(hours);

        return Array(hours, minutes, seconds);
    }

    function show_time_left() {
        $("#larmTime5").val(format_output()[0]);
        $("#larmTime6").val(format_output()[1]);
        $("#larmTime7").val(format_output()[2]);
    }

    function no_time_left() {
		console.log(time_left+"_____");
        stopclocksecond();
		audioElement.play();
		clearTimeout(timer);
    }

    return {
        count: function() {
            countdown();
            show_time_left();
        },
        timer: function() {
            javascript_countdown.count();
			console.log(keep_counting);
            if (keep_counting==0) {
                timer = setTimeout("javascript_countdown.timer();", 1000);
            }
        },
        //Kristian Messer requested recalculation of time that is left
        setTimeLeft: function(t) {
            time_left = t;
            if (keep_counting == 0) {
                javascript_countdown.timer();
            }
        },
        init: function(t) {
            time_left = t;
            //output_element_id = element_id;
            //javascript_countdown.timer();
        }
    };
} ();

$(function() {
    $("#start_button").bind('click',function() {
        var hour = $("#larmTime5").val() * 3600;
        var minute = $("#larmTime6").val() * 60;
        var second = $("#larmTime7").val();
        var countsecond = parseInt(hour) + parseInt(minute) + parseInt(second);
        javascript_countdown.init(countsecond);
        javascript_countdown.timer();
		startclocksecond();
    }) 
	$("#stop_button").bind('click',function() {
        clearTimeout(timer);
		pauseclocksecond();
    })
	$("#pause_button").bind('click',function() {
        clearTimeout(timer);
		stopclocksecond();
        $("#larmTime5").val(initnumber);
        $("#larmTime6").val(initnumber);
        $("#larmTime7").val(initnumber);
    })
	$("#add_button").bind('click',function() {
        if (create) {
            addplan("input");
            $('#cooking').blur(function() {
                submitplan();
            });

        } else {
            alert("creating now");
        }
    })
});

function addplan(tag) {
    var tab = document.getElementById("clock_table1");
    var rowCount = $('#clock_table1 >tbody').length;
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
    var td1 = document.createElement("td");
    td1.style.width = "40% ";
    var div1 = document.createElement("div");
    div1.className = "row3";
    div1.id = "L" + rowCount;
    if (tag == "input") {
        tbody.id = "addtb";
        var input = document.createElement("input");
        input.id = "cooking";
        div1.appendChild(input);
    } else {
        div1.innerHTML = $("#cooking").val();
        tbody.id = "t" + (parseInt(rowCount));
    }
    td1.appendChild(div1);
    var td2 = document.createElement("td");
    td2.style.width = "50% ";
    var div2 = document.createElement("div");
    div2.className = "row4";
    div2.id = "time" + rowCount;
    div2.innerHTML = $("#larmTime5").val() + ":" + $("#larmTime6").val() + ":" + $("#larmTime7").val();
    td2.appendChild(div2);
    var td3 = document.createElement("td");
    td3.style.width = "10%";
    var img = document.createElement("img");
    td3.appendChild(img);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tbody.appendChild(tr);
    tab.appendChild(tbody);
    if (tag == "input") {
        img.src = "image/tools_clock/timer_countdown_save.png";
        img.id = "addplan";
        img.addEventListener("click",
        function() {
            submitplan(img);
        },
        false)

    } else {
        img.src = "image/tools_clock/timer_countdown_delete.png";
        img.id = "img" + (parseInt(rowCount));
        img.addEventListener("click",
        function() {
            deleteplan(rowCount);
        },
        false) 
		div1.addEventListener("click",function() {
            startTask(rowCount);
        },false)
    }

    create = false;
}

function submitplan(e) {

    addplan();
    create = true;
    $("#addtb").remove();

}

function deleteplan(id) {
    $("#t" + id).remove();
}

function startTask(id) {
    var timeTask = $("#time" + id).text();
    $("#larmTime5").val(timeTask.split(":")[0]);
    $("#larmTime6").val(timeTask.split(":")[1]);
    $("#larmTime7").val(timeTask.split(":")[2]);
}
var cse, cs = 1;
function countsecond() {
    if (cs==10) {
        cs = 1;
    }
    $("#larmTime8").html(cs);
    cs += 1;
}

function startclocksecond() {
    cse = setInterval("countsecond()", 10);
}
function pauseclocksecond() {
    clearInterval(cse);
}
function stopclocksecond() {
    clearInterval(cse);
	cs = 0;
	$("#larmTime8").html(cs);
}
var audioElement;
$(document).ready(function() {
	audioElement = document.createElement('audio');
	audioElement.setAttribute('src', 'audio/song.ogg');
	audioElement.load()
	audioElement.addEventListener("load", function() { 
		audioElement.play(); 
	}, true);
});

$(function() {
$("#hour1").click(function(){
	var h=$("#larmTime5").val().split("");
	h[0]++;
	if(h[0]>9){
		h[0]=0;
	}
	$("#larmTime5").val(h[0]+h[1]);
});
$("#hour2").click(function(){
	var h=$("#larmTime5").val().split("");
	h[1]++;
	if(h[1]>9){
		h[1]=0;
	}
	$("#larmTime5").val(h[0]+h[1]);
});
$("#min1").click(function(){
	var m=$("#larmTime6").val().split("");
	m[0]++;
	if(m[0]>5){
		m[0]=0;
	}
	$("#larmTime6").val(m[0]+m[1]);
});
$("#min2").click(function(){
	var m=$("#larmTime6").val().split("");
	m[1]++;
	if(m[1]>9){
		m[1]=0;
	}
	$("#larmTime6").val(m[0]+m[1]);
});
$("#sec1").click(function(){
	var s=$("#larmTime7").val().split("");
	s[0]++;
	if(s[0]>5){
		s[0]=0;
	}
	$("#larmTime7").val(s[0]+s[1]);
});
$("#sec2").click(function(){
	var m=$("#larmTime7").val().split("");
	if(m[1]>9){
		m[1]=0;
	}
	m[1]++;
	$("#larmTime7").val(m[0]+m[1]);
}); 
});
